package com.aabte.springcloudlearn.zuulgatewaydemo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Daniel
 */
@Slf4j
@Component
public class AccessFilter extends ZuulFilter {
    /**
     * 指定过滤器类型：
     * pre: 在请求到达路由前被调用
     * route: 在路由请求时被调用
     * post: 在route和error过滤器之后被调用，最后调用
     * error: 处理请求时发生的错误时被调用
     * static: 返回静态响应，{@link com.netflix.zuul.filters.StaticResponseFilter}实现
     * 以上类型在会创建或添加或运行在FilterProcessor.runFilters(type)
     *
     * @return A String representing that type
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行顺序号，数值越小优先级越高
     * @return 0
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否启动这个过滤器
     * @return true
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤逻辑
     * @return 处理结果
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        log.info("Start run in AccessFilter.");

        // 获取当前请求上下文件
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();
        StringBuffer requestURL = request.getRequestURL();
        String method = request.getMethod();
        log.info("Into AccessFilter.run. url: {}, method: {}", requestURL, method);

        // 校验Token
        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isBlank(accessToken)) {
            log.info("Illegal request.");
            // 使用Zuul过滤请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }

        log.info("End run in AccessFilter.");
        return null;
    }
}
